//
//  HomeViewController.m
//  01 微博
//
//  Created by zhoup on 16/5/14.
//  Copyright © 2016年 zhoup. All rights reserved.
//

#import "HomeViewController.h"
#import "UIView+Frame.h"
#import "UIBarButtonItem+button.h"
#import "ScanViewController.h"
#import "WPTitleButton.h"
#import "WPMenu.h"
#import "DefaultCenterView.h"
#import "AuthViewController.h"

#import "IWStatus.h"
#import "IWUser.h"
#import "IWPhoto.h"

#import "HomeFooterView.h"
#import "UIImageView+WebCache.h"

#import "HomeViewCell.h"


@interface HomeViewController ()<DefaultCenterViewDelegate>


@property(nonatomic,strong) DefaultCenterView *defaultCenterView ;

/**
 *  微博数组(存放着所有的微博数据)
 */
@property (nonatomic, strong) NSMutableArray *statuses;


@property(nonatomic,weak) UIRefreshControl *refreshControl;
@end

@implementation HomeViewController
//-(void)loadView
//{
//    BOOL isLogin =  [WPAccount isLogin];
//    if (isLogin) {
//        
//        self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
//            }
//    else
//    {
//        
//        DefaultCenterView *defaultCenterView = [DefaultCenterView defaultCenterView];
//        defaultCenterView.titleImageName=@"visitordiscover_feed_image_house";
//        
//        defaultCenterView.titleLabelName  = @"当你关注一些人以后，他们发布的最新消息会显示在这里";
//        
//        //    defaultCenterView.rotateImage.hidden = NO;
//        self.defaultCenterView = defaultCenterView;
//        self.view = defaultCenterView;
//        defaultCenterView.delegate = self;
//        [defaultCenterView startRotate];
//    }
//}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // 开始旋转
    if (self.defaultCenterView != nil) {
        [self.defaultCenterView startRotate];
    }
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    // 停止旋转
    if (self.defaultCenterView != nil) {
        [self.defaultCenterView stopRotate];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.estimatedRowHeight = 200;
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    BOOL isLogin =  [WPAccount isLogin];
    if (isLogin) {
        // 加载微博数据
        [self loadNewStatuses:nil];
        
        UIRefreshControl *refreshControl = [[UIRefreshControl alloc]init];
        self.refreshControl = refreshControl;
        [refreshControl addTarget:self action:@selector(loadNewStatuses:) forControlEvents:UIControlEventValueChanged];
        [self.tableView addSubview:refreshControl];
        
        [self.refreshControl beginRefreshing];
    }
    [self setupNav];
  
}


- (void)setupNav
{
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"navigationbar_friendsearch" hightImageName:@"navigationbar_friendsearch_highlighted" target:self action:@selector(test)];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"navigationbar_pop" hightImageName:@"navigationbar_pop_highlighted" target:self action:@selector(scan)];
    
    // 标题
    WPTitleButton *titleBtn = [[WPTitleButton alloc] init];
    [titleBtn setTitle:@"首页" forState:UIControlStateNormal];
    // 设置默认状态图片
    [titleBtn setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    // 设置选中状态图片
    [titleBtn setImage:[UIImage imageNamed:@"navigationbar_arrow_up"] forState:UIControlStateSelected];
    [titleBtn sizeToFit];
    
    // 监听标题按钮点击事件
    [titleBtn addTarget:self action:@selector(titleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.titleView = titleBtn;
}

#pragma mark - 内部控制方法
- (void)titleBtnClick:(WPTitleButton *)titleBtn
{
    // 1.切换按钮的状态
    titleBtn.selected = !titleBtn.selected;
   
    UIView *content  = [[UIView alloc]init];
    //    [content setBackgroundColor:[UIColor redColor]];
    content.frame = CGRectMake(0, 0, 200, 200);
    
//    [WPMenu show:content withView:titleBtn];

    [WPMenu show:content withView:titleBtn dismiss:^{
        NSLog(@"ddd");
    }];
  
}


-(void) test
{
    NSLog(@"test");
}

-(void) scan
{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Scan" bundle:nil];
    ScanViewController *scan =  [sb instantiateInitialViewController];
    
//    ScanViewController *scan = [[ScanViewController alloc]init];
    
    [self presentViewController:scan animated:YES completion:nil];
    
}


-(UIBarButtonItem *)itemWithImage:(NSString *)imageName  hightImageName:(NSString *)hightImageName target:(id)target action:(SEL)action
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:hightImageName] forState:UIControlStateHighlighted];
    btn.size = btn.currentImage.size;
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:btn];
    
    [btn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    
    return item;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.statuses.count;
}


-(void)defaultCenterView:(DefaultCenterView *)defaultCenterView didClickLogin:(UIButton *)loginBtn
{
    NSLog(@"%s",__func__);
    
    AuthViewController *authVc = [[AuthViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:authVc];
    
    [self presentViewController:nav animated:YES completion:nil];

}


-(void)defaultCenterView:(DefaultCenterView *)defaultCenterView didClickRegister:(UIButton *)registerBtn
{
    NSLog(@"%s",__func__);
    
    

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1.创建cell
   HomeViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"customCell" forIndexPath:indexPath];
    
    IWStatus *status = self.statuses[indexPath.row];
    
    cell.status = status;
    
    return cell;
}

/**
 *  加载微博数据
 */
- (void)loadNewStatuses:(UIRefreshControl *)refreshControl
{
    // 1.创建网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 2.封装请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"access_token"] = [WPAccount accountFromSandbox].access_token;
//    parameters[@"uid"] = [WPAccount accountFromSandbox].uid;
    
    parameters[@"count"] = @20;
    
    // 取出数组中第一个元素的ID
    NSString *firstStatusIdstr = [[self.statuses firstObject] idstr];
    
    if (firstStatusIdstr != nil) {
        parameters[@"since_id"] = firstStatusIdstr;
    }
    
    
    // 3.发送请求

    NSString *urlString = @"https://api.weibo.com/2/statuses/home_timeline.json";
    [manager GET:urlString parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        
        // 1.存储获取到得微博数据
        // 获取字典数组
        NSArray *newStatus = responseObject[@"statuses"];
        // 将字典数组转换为模型数据
        NSLog(@"newstatus = %@",newStatus);
        
        // 将字典数组转换为模型数据
        NSArray *models = [IWStatus objectArrayWithKeyValuesArray:newStatus];

        [self.statuses addObjectsFromArray:models];
        
        NSRange range = NSMakeRange(0, models.count);
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
        [self.statuses insertObjects:models atIndexes:indexSet];
        
        // 2.刷新表格
        [self.tableView reloadData];
        
        // 3 结束刷新
        [self.refreshControl endRefreshing];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",error);
       [self.refreshControl endRefreshing];
    }];
}

#pragma mark -懒加载
- (NSMutableArray *)statuses
{
    if (!_statuses) {
        _statuses = [NSMutableArray array];
    }
    return _statuses;
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //
    CGFloat constOffetY = scrollView.contentSize.height + scrollView.contentInset.bottom - scrollView.height;
//
    if (self.tableView.tableFooterView !=nil || self.statuses.count == 0) {
        return;
    }
    if (scrollView.contentOffset.y >= constOffetY) {
        NSLog(@"应该下拉刷新");
        self.tableView.tableFooterView = [HomeFooterView footerView];
        //加载更多的微博
        [self loadMoreStatus];
    }
    
}

/**
 *  加载微博数据
 */
- (void)loadMoreStatus
{
    // 1.创建网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 2.封装请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"access_token"] = [WPAccount accountFromSandbox].access_token;
    //    parameters[@"uid"] = [WPAccount accountFromSandbox].uid;
    
    parameters[@"count"] = @20;
    
    // 取出数组中第一个元素的ID
    NSString *lastStatusIdstr = [[self.statuses lastObject] idstr];
    
    if (lastStatusIdstr != nil) {
        parameters[@"max_id"] = @([lastStatusIdstr longLongValue]-1);
    }
    // 3.发送请求
    
    NSString *urlString = @"https://api.weibo.com/2/statuses/home_timeline.json";
    [manager GET:urlString parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        
        // 1.存储获取到得微博数据
        // 获取字典数组
        NSArray *newStatus = responseObject[@"statuses"];
        // 将字典数组转换为模型数据
        NSLog(@"newstatus = %@",newStatus);
        
        // 将字典数组转换为模型数据
        NSArray *models = [IWStatus objectArrayWithKeyValuesArray:newStatus];
        
        [self.statuses addObjectsFromArray:models];
        // 2.刷新表格
        [self.tableView reloadData];
        // 3 结束刷新
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.tableView.tableFooterView = nil;

        });
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",error);
        self.tableView.tableFooterView = nil;
    }];
}

@end
